package com.wetool.jpa;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.wetool.entity.Commodity;
import com.wetool.entity.Resource;
import com.wetool.entity.SplitCommodityRule;
import com.wetool.feign.InvoicingFeignClient;
import com.wetool.model.CommodityAdd;
import com.wetool.model.CommodityModify;
import com.wetool.model.CommoditySave;
import com.wetool.model.dto.CommodityAdds;
import com.wetool.model.dto.CommodityModifys;
import com.wetool.service.CommodityService;
import com.wetool.service.commodity.ResourceService;
import com.wetool.utils.BeanUtils;
import com.wetool.utils.GS1BarcodeUtil;

/**
 * 仓库事件处理器，可用事件如下： BeforeCreateEvent/AfterCreateEvent 新增前/新增后
 * BeforeSaveEvent/AfterSaveEvent 修改前/修改后 BeforeLinkSaveEvent/AfterLinkSaveEvent
 * 资源链接对象修改前/修改后 BeforeDeleteEvent/AfterDeleteEvent 删除前/删除后
 * 
 * @author lixin
 */

@Component
@RefreshScope
public class CommodityEventHandler {

	@Autowired
	private CommodityService commodityService;
	
	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	private InvoicingFeignClient invoicingFeignClient;
	
	/**
	 * 添加前处理 
	 * @param commodity
	 * @throws IllegalAccessException 
	 * @throws ClassNotFoundException 
	 * @throws IllegalArgumentException 
	 */
	public Commodity beforeCreate(CommodityAdd commodityAdd,Commodity commodity) throws IllegalArgumentException, ClassNotFoundException, IllegalAccessException{
		commodity.setIsDetachable(commodityAdd.isDetachable());//对属性值复制
	    commodity.setInventoryNumber(commodityAdd.getInventoryQuantity());//对属性值复制
		if (!commodity.getIsDetachable()) { //逻辑判断拆分规则是否添加
			commodity.setSplitRule(null);
		}
		String counrt = GS1BarcodeUtil.getCountryCode(commodity.getBarcode());//添加商品归属或其他
		commodity.setCountry(counrt);//添加商品归属或其他
		if (commodityAdd.getResource() != null) {//添加图片资源
			List<Resource> list = Arrays.asList(commodityAdd.getResource());
			commodity.setResources(list);
		}
		/* 编码规则校验 */
		//Boolean flag = Ean13Util.getVerificationEan13(commodity.getBarcode());
		//commodity.setIsGs1(flag);
		// 使用JPpinying jar包方法转换中文全拼
		String str1 = PinyinHelper.convertToPinyinString(commodity.getName(), "", PinyinFormat.WITHOUT_TONE);
		commodity.setPinyin(str1);
		// 使用JPpinying jar包方法转换拼音首字母
		commodity.setPinyinShorthand(PinyinHelper.getShortPinyin(commodity.getName()));
		// 对上传图片处理处理属性
		String url = null;
		List<Resource> rs = new ArrayList<>();
		if (commodity.getResources() != null) {
			rs = commodity.getResources();
		}
		for (Resource resource : rs) {
			if (resource != null) {
				url = resource.getResUrl();
			}
			/* 对图片信息保存 */
			if (url != null && !"".equals(url)) {
				if (url.indexOf("_w") != -1  && url.indexOf("_h") != -1 ) {
					String width = url.substring(url.indexOf("_w") + 2, url.lastIndexOf("_"));
					String heigth = url.substring(url.indexOf("_h") + 2, url.lastIndexOf("."));
					resource.setWidth(Float.valueOf(width));
					resource.setHeigth(Float.valueOf(heigth));
				} else {
					resource.setWidth(0);
					resource.setHeigth(0);
				}
				rs = resourceService.save(rs);
				commodity.setResources(rs);
				commodity.setResource(null);
			} else {
				commodity.setResources(null);
			}
		}
		return commodity;
	}

	/**
	 * 修改前对数据处理
	 * @param commodityModify
	 * @param commodity
	 * @return
	 * @throws IllegalArgumentException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 */
	public Commodity beforeSave(CommodityModify commodityModify,Commodity commodity) throws IllegalArgumentException, ClassNotFoundException, IllegalAccessException {
		/* 修改时自动设置修改时间 */
		commodityModify.setUpdateDate(new Timestamp(System.currentTimeMillis()));
		commodity.setInventoryNumber(commodityModify.getInventoryQuantity());//属性值复制
		commodity.setIsDetachable(commodityModify.isDetachable());//属性值复制
		commodityService.getSplit(commodityModify,commodity);//拆分数据处理
		if (commodityModify.getResource() != null) {//图片数据处理
			resourceService.resourceHandle(commodityModify.getResource(), commodity);
		}
		/* 编码规则校验 */
		//Boolean flag = Ean13Util.getVerificationEan13(commodity.getBarcode());
		//commodity.setIsGs1(flag);
		// 使用JPpinying jar包方法转换中文全拼
		String str1 = PinyinHelper.convertToPinyinString(commodity.getName(), "", PinyinFormat.WITHOUT_TONE);
		commodity.setPinyin(str1);
		// 使用JPpinying jar包方法转换拼音首字母
		commodity.setPinyinShorthand(PinyinHelper.getShortPinyin(commodity.getName()));
		// 对上传图片处理
		String url = null;
		List<Resource> rs = new ArrayList<>();
		if (commodity.getResources() != null) {
			rs = commodity.getResources();
		}
		for (Resource resource : rs) {
			if (rs != null) {
				url = resource.getResUrl();
			}
			String counrt = GS1BarcodeUtil.getCountryCode(commodity.getBarcode());
			commodity.setCountry(counrt);//添加商品归属或其他
			//对图片路径处理
			if (url != null && !"".equals(url)) {
				if (url.indexOf("_w") != -1  && url.indexOf("_h") != -1 ) {
					String width = url.substring(url.indexOf("_w") + 2, url.lastIndexOf("_"));
					String heigth = url.substring(url.indexOf("_h") + 2, url.lastIndexOf("."));
					resource.setWidth(Float.valueOf(width));
					resource.setHeigth(Float.valueOf(heigth));
				} else {
					resource.setWidth(0);
					resource.setHeigth(0);
				}
				rs = resourceService.save(rs);
				commodity.setResources(rs);
				commodity.setResource(null);
			} else {
				commodity.setResources(null);
			}
		}
		return commodity;
	}
	
	/**
	 * 同步商品数据在商品库存
	 * @param commodity
	 * @return
	 */
	public String handleCommodity(Commodity commodity) {
		CommoditySave c = new CommoditySave();
		BeanUtils.copyProperties(commodity, c);
		c.setInventoryQuantity(commodity.getInventoryNumber());
		c.setInventoryWarningQuantity(commodity.getWarningNumber());
		String i = invoicingFeignClient.updateShopCommodity(c);//对库存商品信息数据修改
		return i;
	}

	/**
	 * 保存前处理
	 * @param commodityAdds
	 * @param commodity
	 * @throws IllegalArgumentException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 */
	public void beforeCreate(CommodityAdds commodityAdds, Commodity commodity) throws IllegalArgumentException, ClassNotFoundException, IllegalAccessException {
		if (!commodity.getIsDetachable()) { //逻辑判断拆分规则是否添加
			commodity.setSplitRule(null);
		}
		commodity.setInventoryNumber(commodityAdds.getInventoryQuantity());//属性值复制
		String counrt = GS1BarcodeUtil.getCountryCode(commodity.getBarcode());//添加商品归属或其他
		commodity.setCountry(counrt);//添加商品归属或其他
		// 使用JPpinying jar包方法转换中文全拼
		String str1 = PinyinHelper.convertToPinyinString(commodity.getName(), "", PinyinFormat.WITHOUT_TONE);
		commodity.setPinyin(str1);
		// 使用JPpinying jar包方法转换拼音首字母
		commodity.setPinyinShorthand(PinyinHelper.getShortPinyin(commodity.getName()));
		if (commodityAdds.getResource() != null) {//添加图片资源
			this.setResource(commodityAdds.getResource(),commodity);
		}
		if (commodityAdds.getSplitRule()!= null && commodityAdds.getIsDetachable()) {
			this.setSplitRule(commodityAdds.getSplitRule(),commodity);
		}
	}
	
	/**
	 * 修改前处理
	 * @param commodityModifys
	 * @param commodity
	 * @throws IllegalAccessException 
	 * @throws ClassNotFoundException 
	 * @throws IllegalArgumentException 
	 */
	public void beforeSave(CommodityModifys commodityModifys, Commodity commodity) throws IllegalArgumentException, ClassNotFoundException, IllegalAccessException {
		if (!commodity.getIsDetachable()) { //逻辑判断拆分规则是否添加
			commodity.setSplitRule(null);
		}
		commodity.setInventoryNumber(commodityModifys.getInventoryQuantity());//属性值复制
		String counrt = GS1BarcodeUtil.getCountryCode(commodity.getBarcode());//添加商品归属或其他
		commodity.setCountry(counrt);//修改商品归属或其他
		// 使用JPpinying jar包方法转换中文全拼
		String str1 = PinyinHelper.convertToPinyinString(commodity.getName(), "", PinyinFormat.WITHOUT_TONE);
		commodity.setPinyin(str1);
		// 使用JPpinying jar包方法转换拼音首字母
		commodity.setPinyinShorthand(PinyinHelper.getShortPinyin(commodity.getName()));
		if (commodityModifys.getResource() != null) {//修改图片资源
			this.setResource(commodityModifys.getResource(),commodity);
		}
		if (commodityModifys.getSplitRule()!= null && commodityModifys.getIsDetachable()) {
			this.setSplitRule(commodityModifys.getSplitRule(),commodity);
		}
	}
	
	/**
	 * 图片资源处理
	 * @param resource
	 * @return
	 */
	private Resource resource(Resource resource) {
		String url = resource.getResUrl();
		if (url == null || "".equals(url)) {
			return resource = null;
		}
		if(url.indexOf("_w") != -1) {
			String width = url.substring(url.indexOf("_w") + 2, url.lastIndexOf("_"));
			String heigth = url.substring(url.indexOf("_h") + 2, url.lastIndexOf("."));
			resource.setWidth(Float.valueOf(width));
			resource.setHeigth(Float.valueOf(heigth));
		}else {
			resource.setWidth(0);
			resource.setHeigth(0);
		}
		return resource;
	}
	
	/**
	 * 图片属性复制
	 * @param obj
	 * @param commodity
	 */
	private void setResource(Object obj,Commodity commodity) {
		Resource resource = new Resource(); 
		if (commodity.getResources()!= null && !commodity.getResources().isEmpty()) {
			resource = commodity.getResources().get(0);
		}
		BeanUtils.copyProperties(obj, resource);
		resource = this.resource(resource);
		if (resource != null) {
			List<Resource> rs = new ArrayList<>();
			rs.add(resource);
			commodity.setResources(rs);
		}
	}
	
	/**
	 * 拆分属性保存
	 * @param obj
	 * @param commodity
	 */
	private void setSplitRule(Object obj,Commodity commodity) {
		SplitCommodityRule splitCommodityRule = null;
		if (commodity.getSplitRule() == null) {
			splitCommodityRule = new SplitCommodityRule();
		}
		if (commodity.getSplitRule() != null) {
			splitCommodityRule = commodity.getSplitRule();
		}
		BeanUtils.copyProperties(obj, splitCommodityRule);
		commodity.setSplitRule(splitCommodityRule);
	}

}
